import { reqGetOrderDetail } from '../../api/orderdetail';
import { toast } from '../../utils/extendApi';

Page({
  data: {
    orderDetail: null,
    loading: true,
    error: null,
    retryCount: 0,
    maxRetryCount: 2,
    showRetryButton: false,
    orderId: null
  },

  onLoad: function(options) {
    console.log('[Page] 页面加载，参数:', options);
    
    if (!options.orderId) {
      console.error('[Page] 缺少订单ID参数');
      this.handleError('缺少订单ID参数');
      return;
    }
    
    this.setData({ orderId: options.orderId });
    this.fetchOrderDetail(options.orderId);
  },

  fetchOrderDetail: function(orderId) {
    console.log('[Page] 开始获取订单详情，订单ID:', orderId);
    
    this.setData({ 
      loading: true, 
      error: null,
      orderDetail: null,
      showRetryButton: false
    });
    
    reqGetOrderDetail(orderId)
      .then(response => {
        console.log('[Page] 获取订单详情成功:', response);
        
        if (!response || !response.data) {
          throw new Error('无效的响应数据');
        }
        
        this.setData({
          orderDetail: this.processOrderData(response.data),
          loading: false,
          retryCount: 0
        });
      })
      .catch(error => {
        console.error('[Page] 获取订单详情失败:', error);
        
        // 自动重试逻辑
        if (this.data.retryCount < this.data.maxRetryCount) {
          const retryCount = this.data.retryCount + 1;
          console.log(`[Page] 将在3秒后重试 (${retryCount}/${this.data.maxRetryCount})`);
          
          this.setData({ retryCount });
          
          setTimeout(() => {
            this.fetchOrderDetail(orderId);
          }, 3000);
        } else {
          this.handleError(error.message || '获取订单详情失败');
        }
      });
  },

  processOrderData: function(rawData) {
    console.log('[Page] 原始订单数据:', rawData);
    
    // 订单基础信息默认值（不含蛋糕字段）
    const defaultOrderData = {
      orderid: '',
      userid: '',
      ordernum: '',
      ordertime: '',
      orderstatus: 0,
      refund: 0,
      orderprice: 0,
      orderecount: 0, // 总商品数量（后端返回）
      orderdiscussif: 0,
      userreason: '',
      shopreply: '',
      payid: '',
      deliverypay: 0,
      remark: '',
      consignee: '',
      phone: '',
      province: '',
      city: '',
      district: '',
      address: '',
      discountname: '',
      maxmoney: 0,
      money: 0,
      cakesList: [] // 多蛋糕列表（核心字段）
    };
    
    // 合并订单基础数据
    const orderData = { ...defaultOrderData, ...rawData };
    console.log('[Page] 合并后的订单基础数据:', orderData);

    // 处理多蛋糕信息（计算每个蛋糕金额并汇总）
    let totalProductAmount = 0; // 所有商品总金额
    const processedCakes = orderData.cakesList.map(cake => {
      // 单个蛋糕默认值
      const defaultCake = {
        cakeId: 0,
        cakeName: '未知商品',
        cakeDesc: '',
        cakePrice: 0,
        cakePricebig: 0,
        cakeUrl: '',
        cakesize: 0, // 0=4寸，1=6寸
        cakeSales: 0
      };
      const cakeData = { ...defaultCake, ...cake };
      
      // 计算单个蛋糕单价（根据尺寸）
      const unitPrice = cakeData.cakesize === 1 ? cakeData.cakePricebig : cakeData.cakePrice;
      // 单个蛋糕金额（默认1件，若有数量字段可改为 cakeData.count * unitPrice）
      const cakeAmount = unitPrice * 1; 
      totalProductAmount = orderData.orderprice + orderData.money - 
      orderData.deliveryFee; // 累加总商品金额
      
      return {
        id: cakeData.cakeId,
        name: cakeData.cakeName,
        desc: cakeData.cakeDesc,
        unitPrice: unitPrice,
        size: cakeData.cakesize === 1 ? '6寸' : '4寸',
        image: cakeData.cakeUrl || '/images/default-product.png',
        amount: cakeAmount, // 单个蛋糕小计
        sales: cakeData.cakeSales
      };
    });

    // 计算订单总金额
    const totalAmount =  orderData.orderprice;
    const allProductAount = orderData.orderprice + orderData.money - orderData.deliverypay;
    return {
      // 订单基本信息
      orderId: orderData.orderid,
      userId: orderData.userid,
      orderNum: orderData.ordernum,
      orderTime: this.formatDate(orderData.ordertime),
      orderStatus: this.getStatusText(orderData.orderstatus, orderData.refund),
      orderCount: orderData.orderecount || processedCakes.length, // 总商品数量
      totalAmount: totalAmount, // 最终实付款
      productAmount: allProductAount, // 所有商品总金额
      isEvaluated: orderData.orderdiscussif === 1,
      refundStatus: orderData.refund,
      userReason: orderData.userreason,
      shopReply: orderData.shopreply,
      
      // 多蛋糕列表（核心修改：替换原cakeInfo为cakesList数组）
      cakesList: processedCakes,
      
      // 支付信息
      payInfo: {
        payId: orderData.payid,
        deliveryFee: orderData.deliverypay,
        remark: orderData.remark,
        originalPrice: totalProductAmount // 商品总金额
      },
      
      // 优惠券信息
      discountInfo: orderData.discountname ? {
        name: orderData.discountname,
        maxMoney: orderData.maxmoney,
        discountMoney: orderData.money
      } : null,
      
      // 地址信息
      addressInfo: {
        consignee: orderData.consignee,
        phone: this.formatPhone(orderData.phone),
        province: orderData.province,
        city: orderData.city,
        district: orderData.district,
        detailAddress: orderData.address
      },
      
      // 原始数据（用于调试）
      _rawData: rawData
    };
  },

  // 日期格式化
  formatDate: function(dateString) {
    if (!dateString) return '';
    const date = new Date(dateString);
    return `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
  },

  // 获取状态文本
  getStatusText: function(status, refund) {
    const statusMap = {
      0: '待修改',
      1: '待配送',
      2: '待收货', 
      3: '已完成'
    };
    
    if (refund === 1) return '退款中';
    if (refund === 2) return '已退款';
    
    return statusMap[status] || '未知状态';
  },

  // 手机号脱敏
  formatPhone: function(phone) {
    if (!phone) return '';
    return phone.replace(/(\d{3})(\d{4})(\d{4})/, '$1****$3');
  },

  // 错误处理
  handleError: function(message) {
    console.error('[Page] 处理错误:', message);
    
    toast({ 
      title: message, 
      icon: 'none',
      duration: 3000
    });
    
    this.setData({ 
      loading: false,
      error: message
    });
    
    // 提供手动刷新按钮
    setTimeout(() => {
      this.setData({
        showRetryButton: true
      });
    }, 3000);
  },

  // 手动重试
  onRetry: function() {
    console.log('[Page] 用户手动重试');
    this.setData({
      showRetryButton: false,
      retryCount: 0
    });
    this.fetchOrderDetail(this.data.orderId);
  },

  // 返回上一页
  handleBack: function() {
    wx.navigateBack();
  },

  // 图片加载失败处理（适配多蛋糕）
  handleImageError: function(e) {
    const index = e.currentTarget.dataset.index; // 获取当前蛋糕索引
    console.log(`[Page] 第${index+1}个商品图片加载失败，使用默认图`);
    
    // 动态更新对应蛋糕的图片地址
    const cakesList = this.data.orderDetail.cakesList;
    cakesList[index].image = '/images/default-product.png';
    this.setData({
      'orderDetail.cakesList': cakesList
    });
  }
});